package org.jcut.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.jcut.bean.Orderform;
import org.jcut.bean.User;
import org.jcut.data.Data;
import org.jcut.service.UserService;
import org.jcut.tools.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@SuppressWarnings(value = "all")
@RestController
@RequestMapping("/user")
public class UserController {
	@Value("${imgpath}")
	String path;
	@Autowired
	private Data data;
	@Autowired
	private RedisTemplate  redisTemplate;
	@Autowired
	private UserService service;
	@RequestMapping("/register")
	public Object add(@Valid User user,Errors e) {
		String id=UUID.randomUUID().toString();
		user.setId(id);
		user.setBalance(0.0);
		user.setTime(new Date());
		user.setPwd(MD5Util.encode2hex(user.getPwd()));
		int i=0;
		List<ObjectError> error=e.getAllErrors();
		
		for(ObjectError ee:error) {
			data.setMsg(ee.getDefaultMessage());			
		}
		if(error.size()==0) {
			i=service.add(user);
		}
		
		if(i>0) {
			data.setMsg("添加成功！");
			data.setStatus("1");
			data.setData(i);
		}else {
			data.setStatus("服务器异常");
			data.setStatus("0");
			data.setData(i);
		}
		
		
		return data;
	}
	
	@RequestMapping(value="/select",params = {"pwd","tel"})
	public Object select(User user) {
		user.setPwd(MD5Util.encode2hex(user.getPwd()));
		/**
		 * 使用Shiro编写认证操作
		 */
		//1.获取Subject
		Subject subject = SecurityUtils.getSubject();
		
		//2.封装用户数据
		UsernamePasswordToken token = new UsernamePasswordToken(user.getTel(),user.getPwd());
		
		
			try {
				subject.login(token);
				User user1=service.select(user).get(0);
				List list=new ArrayList<User>();
				list.add(user1);
				redisTemplate.opsForValue().set(user1.getId(), list, 1l, TimeUnit.HOURS);
				data.setData(user1.getId());
				data.setStatus("1");
				data.setMsg("登陆成功！");
			}catch(Exception e) {

				data.setData("0");
				data.setStatus("0");
				data.setMsg("登陆失败！");
			}
		
		return data;
	}
	@RequestMapping(value="/login",params = {"id"})
	public Object getUser(String id) {
		List<User> u=(List<User>)redisTemplate.opsForValue().get(id);
		if(u.size()>0) {
			for(User list:u) {
				if(id.equals(list.getId())) {
					data.setData(list);
					data.setMsg("已登陆");
					data.setStatus("1");
				}else {
					data.setData("0");
					data.setMsg("未登陆");
					data.setStatus("0");
				}
					
			}
		}else{
			data.setData("0");
			data.setMsg("未登陆");
			data.setStatus("0");
		}
	
		return data;
	}
	@RequestMapping("/updateInfo")
	public Object updateInfo(@Valid User user,Errors e) {
		List<ObjectError> error=e.getAllErrors();
		for(ObjectError ee:error) {
			data.setMsg(ee.getDefaultMessage());
		}
		if(error.size()==0) {
			int i=service.updateInfo(user);
			if(i>0) {
				data.setData(i);
				data.setMsg("修改成功！");
				data.setStatus("1");
			}else {
				data.setData(i);
				data.setMsg("服务器异常！");
				data.setStatus("0");
			}
			
		}else {
			data.setData("0");
			data.setStatus("0");
		}
		
		return data;
	}
	@RequestMapping("/addImg")
	public Object addImg(@RequestParam("id")String id,@RequestParam("img")MultipartFile file) {
		try {
			String type[]=file.getContentType().split("/");
			if(type.length>1&&type[0].equals("image")) {
				String imgName=UUID.randomUUID().toString()+".jpg";
				file.transferTo(new File(path+imgName));
				User user=new User();
				user.setId(id);
				user.setImg("imgs/"+imgName);
				int i=service.addImg(user);
				if(i>0) {
					selectById(id);
					data.setData(imgName);
					data.setMsg("上传成功！");
					data.setStatus("1");
				}else {
					data.setData(i);
					data.setMsg("服务器异常！");
					data.setStatus("0");
				}
			}else {
				data.setData("0");
				data.setMsg("只支持图片！");
				data.setStatus("0");
			}
			
		} catch (IllegalStateException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return data;
	}
	@RequestMapping(value="/updatePwd",params = {"pwd","id"})
	public Object updatePwd(@Valid User user,Errors e) {
		List<ObjectError> error=e.getAllErrors();
		
		for(ObjectError ee:error) {
			data.setMsg(ee.getDefaultMessage());
		}
		if(error.size()==0) {
			user.setPwd(MD5Util.encode2hex(user.getPwd()));
			int i=service.updatePwd(user);
			if(i>0) {
			data.setData(i);
			data.setMsg("修改成功！");
			data.setStatus("1");	
			}else {
				data.setData(i);
				data.setMsg("服务器异常！");
				data.setStatus("0");	
			}
				
			
		}else {
			data.setData("0");
		
			data.setStatus("0");
		}
		
		return data;
	}
	@RequestMapping("/delete")
	public Object delete(User user) {
		int i=service.delete(user);
		if(i>0) {
			data.setData(i);
			data.setMsg("删除成功");
			data.setStatus("1");
		}else {
			data.setData(i);
			data.setMsg("服务器异常！");
			data.setStatus("0");
		}
		return data;
	}
	@RequestMapping(value="/findTel",params = {"tel"})
	public Object findTel(@RequestParam("tel")String tel) {
			long i=service.findTel(tel);
			if(i>0) {
				data.setData("0");
				data.setMsg("手机号已注册");
				data.setStatus("0");
			}else {
				data.setData("1");
				data.setMsg("手机号未注册");
				data.setStatus("1");
			}
		return data;
	}
	public void selectById(String id) {
		
		
		User user=service.selectById(id);
		List<User> list=new ArrayList<User>();
		list.add(user);
		redisTemplate.opsForValue().set(id, list, 1l, TimeUnit.HOURS);
	}
	
	@RequestMapping("/adminSelect")
	public Object adminSelect(@RequestParam(value="pageNum",required = false)String pageNum,@RequestParam(value="pageSize",required = false) String pageSize) {
		
		if ((pageNum != null && !("".equals(pageNum))) && (pageSize != null && !("".equals(pageSize)))) {
			PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		}
		PageInfo<User> pageInfo = new PageInfo<>(service.adminSelect());
		
		data.setData(pageInfo);
		data.setMsg("查询成功");
		data.setStatus("1");
		return data;
	}
	@RequestMapping("/selectByTel")
	public Object selectByTel(String tel) {
		data.setData(service.selectByTel(tel));
		data.setStatus("1");
		data.setMsg("查询成功");
		return data;
	}
}
